package com.link.base.base.home.controller;

import com.link.base.base.message.model.Message;
import com.link.base.base.message.service.MessageService;
import com.link.base.user.model.CoreUser;
import com.link.base.base.approval.model.Flow;
import com.link.base.base.approval.service.FlowService;
import com.link.base.base.common.model.Announce;
import com.link.base.base.common.service.AnnounceService;
import com.link.base.base.home.model.PageConfig;
import com.link.base.base.home.service.HomeService;
import com.link.base.base.home.service.PageConfigService;
import com.link.base.base.report.model.PortalSalesAmount;
import com.link.base.base.report.service.PortalReportService;
import com.link.base.base.system.service.PeriodService;
import com.link.base.base.workplan.model.Workplan;
import com.link.base.base.workplan.service.WorkplanService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 *
 * created: unknown
 * updated: weixuan
 * comments:
 */
@Controller
@RequestMapping("/link/home")
public class HomeController {

    @Resource
    private HomeService homeService;

    @Resource
    private PageConfigService pageConfigService;

    @Resource
    private FlowService flowService;

    @Resource
    private MessageService messageService;

    @Resource
    private AnnounceService announceService;

    @Resource
    private WorkplanService workplanService;

    @Resource
    private PeriodService periodService;

    @Resource
    private PortalReportService portalReportService;

    public static final String WORKPLAN_STATUS_RUNNING = "RUNNING";
    public static final String HOME_PAGE_TYPE_STATISTICS = "Statistics";
    public static final String HOME_PAGE_TYPE_PARTS = "Parts";
    public static final String PERIOD_TYPE_YEAR = "Year";

    @RequestMapping(value = "/mainjsp")
    @ResponseBody
    public ModelAndView main(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        try {
            mav.setViewName("main/home");
            mav.addObject("clueCount", homeService.queryCLueCurentWeekCount());
            mav.addObject("accountCount", homeService.queryAccountCurentWeekCount());
            mav.addObject("orderCount", homeService.queryOrderCurentWeekCount());
            mav.addObject("activityCount", homeService.queryActivityCurentWeekCount());
            mav.addObject("workplanCount", homeService.queryWorkPlanCurentWeekCount());
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mav;
    }

    @RequestMapping(value = "/main")
    public Map<String, Object> getMain(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, Object> mainmsg = new HashMap<String, Object>();
            mainmsg.put("clueCount", homeService.queryCLueCurentWeekCount());
            mainmsg.put("accountCount", homeService.queryAccountCurentWeekCount());
            mainmsg.put("orderCount", homeService.queryOrderCurentWeekCount());
            mainmsg.put("activityCount", homeService.queryActivityCurentWeekCount());
            mainmsg.put("workplanCount", homeService.queryWorkPlanCurentWeekCount());
            result.put("success", true);
            result.put("result", mainmsg);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     *
     * @author weixuan
     * @created 2019-01-15
     * @throws Exception
     * 查询系统首页加载所有明细数据
     */
    @RequestMapping(value = "/getReportData")
    public Map<String, Object> getData(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Object> rows = new ArrayList<Object>();
            CoreUser user = UserUtil.getUser();
            Long userId = user.getId();

            /** 获取当前时间的年期间*/
            Calendar cal = Calendar.getInstance();
            String nowYear = String.valueOf(cal.get(Calendar.YEAR));
            String startDt = nowYear + "-01-01 00:00:00";
            String endDt = nowYear + "-12-31 23:59:59";
            /** 查询用户首页自定义明细栏菜单 */
            PageConfig conf = new PageConfig();
            conf.setPageType(HOME_PAGE_TYPE_PARTS);
            conf.setViewStatus("Y");
            conf.setUserId(userId);
            List<PageConfig> pageConfigList = pageConfigService.queryAll(conf);

            /** 遍历菜单，绑定结果集 */
            for (PageConfig item : pageConfigList) {
                int orginSortNum = item.getOrginSortNum();
                Map<String, Object> obj = new HashMap<String, Object>();
                obj.put("pageName",item.getPageName());
                obj.put("urlId",Long.toString(item.getUrlId()));
                obj.put("url",item.getUrl());
                obj.put("pageType",item.getPageType());
                obj.put("viewStatus",item.getViewStatus());
                obj.put("turnsUrl",item.getTurnsUrl());
                obj.put("sortNumber",item.getSortNumber());
                obj.put("orginSortNum", item.getOrginSortNum());
                switch (orginSortNum) {
                    case 1:
                        /** 我的订单年期间销量报表 */
                        PortalSalesAmount s2 = new PortalSalesAmount();
                        s2.setAttr1(startDt);
                        s2.setAttr2(endDt);
                        List<PortalSalesAmount> salesAmountList = portalReportService.queryYearPeriodSales(s2);
                        obj.put("data", salesAmountList);
                        rows.add(obj);
                        break;
                   /* case 2:
                        *//** 我的客户类型报表 *//*
                        PortalAccountTypeReport s1 = new PortalAccountTypeReport();
                        List<PortalAccountTypeReport> accntTypeList = portalReportService.queryAccntTypeReportByPostn(s1);
                        obj.put("data", accntTypeList);
                        rows.add(obj);
                        break;*/
                    /** 我的未完成工作计划 */
                    case 2:
                        Workplan w = new Workplan();
                        w.setStatus(WORKPLAN_STATUS_RUNNING);
                        w.setCreatedBy(userId);
                        List<Workplan> workplansList = workplanService.queryByExamplePage(w);
                        obj.put("data", workplansList);
                        rows.add(obj);
                        break;
                    case 3:
                        /** 我的待处理流程 */
                        QueryParams qps3 = new QueryParams();
                        qps3.setSort("created");
                        qps3.setOrder("desc");
                        Flow t = (Flow) BasicModel.transformClass(Flow.class, qps3);
                        t.setAttr1(String.valueOf(userId));
                        t.setPage(1);
                        t.setRows(7);
                        List<Flow> flowList = flowService.queryFlowListPage(t);
                        obj.put("data", flowList);
                        rows.add(obj);
                        break;
                    case 4:
                        /** 我的未读消息 */
                        QueryParams qps4 = new QueryParams();
                        qps4.setSort("created");
                        qps4.setOrder("desc");
                        Message p = BasicModel.transformClass(Message.class, qps4);
                        p.setPage(1);
                        p.setRows(7);
                        p.setUserId(userId);
                        List<Message> messageList = messageService.queryByExamplePage(p);
                        obj.put("data", messageList);
                        rows.add(obj);
                        break;
                    case 5:
                        /** 我发起正运行申请 */
                        QueryParams qps5 = new QueryParams();
                        qps5.setSort("created");
                        qps5.setOrder("desc");
                        Flow f = (Flow) BasicModel.transformClass(Flow.class, qps5);
                        f.setPage(1);
                        f.setRows(7);
                        List<Flow> applyList = flowService.queryMyFlowListPage(f);
                        obj.put("data", applyList);
                        rows.add(obj);
                        break;
                    case 6:
                        /** 我的未读公告 */
                        QueryParams qps6 = new QueryParams();
                        qps6.setSort("created");
                        qps6.setOrder("desc");
                        Announce a = (Announce) BasicModel.transformClass(Announce.class, qps6);
                        a.setPage(1);
                        a.setRows(7);
                        List<Announce> announceList = announceService.queryMyAnnouncePage(a,userId);
                        obj.put("data", announceList);
                        rows.add(obj);
                        break;
                    default:
                        break;
                }
            }
            result.put("success", true);
            result.put("result", rows);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     *
     * @author weixuan
     * @created 2019-01-15
     * @throws Exception
     * 查询系统首页的所有统计数据
     */

    @RequestMapping(value = "/getCountData")
    public Map<String, Object> getCountData(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Object> rows = new ArrayList<Object>();
            /** 查询用户首页自定义统计栏菜单 */
            PageConfig conf = new PageConfig();

            CoreUser user = UserUtil.getUser();
            Long userId = user.getId();
            conf.setUserId(userId);
            conf.setPageType(HOME_PAGE_TYPE_STATISTICS);
            conf.setViewStatus("Y");
            List<PageConfig> pageConfigList = pageConfigService.queryAll(conf);

            /** 遍历菜单，给菜单绑定统计值 */
            for (PageConfig item : pageConfigList) {
                int orginSortNum = item.getOrginSortNum();
                Map<String, Object> obj = new HashMap<String, Object>();
                obj.put("pageName",item.getPageName());
                obj.put("urlId",item.getUrlId());
                obj.put("url",item.getUrl());
                obj.put("pageType",item.getPageType());
                obj.put("viewStatus",item.getViewStatus());
                obj.put("turnsUrl",item.getTurnsUrl());
                obj.put("sortNumber",item.getSortNumber());
                switch (orginSortNum) {
                    case 1:
                        /** 我的待审批流程数量 */
                        obj.put("count", homeService.queryMyFlowCount());
                        rows.add(obj);
                        break;
                    case 2:
                        /** 我的未阅读消息数量 */
                        obj.put("count", homeService.queryMyNewsCount());
                        rows.add(obj);
                        break;
                    case 3:
                        /** 我的未阅读公告数量 */
                        obj.put("count", homeService.queryMyAnnounceCount());
                        rows.add(obj);
                        break;
                    case 4:
                        /** 我的未完成工作计划数量 */
                        obj.put("count", homeService.queryMyWorkPlanCount());
                        rows.add(obj);
                        break;
                    case 5:
                        /** 我发起正运行申请数量 */
                        obj.put("count", homeService.queryMyApplyCount());
                        rows.add(obj);
                        break;
                    default:
                        break;
                }
            }
            result.put("success", true);
            result.put("result", rows);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
